package com.ninetaildemonfox.zdl.socialproject.mvp.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.JsonObject;
import com.hyphenate.easeui.utils.map.JSONUtils;
import com.kongzue.baseokhttp.HttpRequest;
import com.kongzue.baseokhttp.listener.ResponseListener;
import com.kongzue.baseokhttp.util.Parameter;
import com.kongzue.dialog.interfaces.OnDialogButtonClickListener;
import com.kongzue.dialog.interfaces.OnDismissListener;
import com.kongzue.dialog.interfaces.OnMenuItemClickListener;
import com.kongzue.dialog.util.BaseDialog;
import com.kongzue.dialog.v3.BottomMenu;
import com.kongzue.dialog.v3.CustomDialog;
import com.kongzue.dialog.v3.MessageDialog;
import com.kongzue.dialog.v3.TipDialog;
import com.kongzue.dialog.v3.WaitDialog;
import com.kongzue.takephoto.TakePhotoUtil;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.ui.ImagePreviewDelActivity;
import com.ninetaildemonfox.zdl.socialproject.base.BaseActivity;
import com.ninetaildemonfox.zdl.socialproject.R;
import com.ninetaildemonfox.zdl.socialproject.config.Constants;
import com.ninetaildemonfox.zdl.socialproject.data.entity.EventMessage;
import com.ninetaildemonfox.zdl.socialproject.http.https.Model;
import com.ninetaildemonfox.zdl.socialproject.mvp.contract.WxZhiFu;
import com.ninetaildemonfox.zdl.socialproject.mvp.ui.adapter.ImageViewAdp;
import com.ninetaildemonfox.zdl.socialproject.utils.ToastUtil;
import com.ninetaildemonfox.zdl.socialproject.utils.dialog.BottomDialog;
import com.ninetaildemonfox.zdl.socialproject.utils.dialog.adapter.PayAdapter;
import com.ninetaildemonfox.zdl.socialproject.utils.dialog.bean.PayNamePayBean;
import com.ninetaildemonfox.zdl.socialproject.wxapi.PayResult;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author NineTailDemonFox
 * @date 2019/7/22 11:15
 * 功能描述：发布约会
 * 联系方式：1037438704@qq.com
 */
public class PublishAnAppoointmentActivity extends BaseActivity implements WxZhiFu {
    @BindView(R.id.image_left_finish)
    ImageView imageleftFinish;
    @BindView(R.id.text_right)
    TextView textRight;
    @BindView(R.id.text_center)
    TextView textCenter;
    @BindView(R.id.text_expect)
    TextView textExpect;
    @BindView(R.id.text_renzheng)
    TextView text_renzheng;
    @BindView(R.id.text_city)
    TextView textCity;
    @BindView(R.id.text_time)
    TextView textTime;
    @BindView(R.id.text_preservation)
    TextView textPreservation;
    @BindView(R.id.fl_time)
    FrameLayout flTime;
    @BindView(R.id.edit_remarks)
    EditText editRemarks;
    @BindView(R.id.text_can_comment)
    TextView textCanComment;
    @BindView(R.id.recyclerVIew)
    RecyclerView recyclerVIew;
    @BindView(R.id.text_time_1)
    TextView textTime_1;
    private int thisCont = 1;
    private String cityId;
    private String textExpectId;
    private Drawable drawable;
    private ImageViewAdp adp;
    public ImageItem imageItem;
    private List<ImageItem> list = new ArrayList<>();
    private int maxImgCount = 4;
    private File file1, file2, file3, file4;
    private String namappointment_ame;
    public static int publishAnAppoointment = 1;
    public static final int IMAGE_ITEM_ADD = -1;
    public static final int REQUEST_CODE_SELECT = 100;
    public static final int REQUEST_CODE_PREVIEW = 101;

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_publish_an_appoointment;
    }

    @Subscribe
    @Override
    public void onInitialization(Bundle bundle) {
        moenyHttp();
        EventBus.getDefault().register(this);

        imageleftFinish.setVisibility(View.VISIBLE);
        textCenter.setText("发布约会");
        recyclerVIew.setLayoutManager(new GridLayoutManager(this, 4));
        recyclerVIew.setHasFixedSize(true);
        adp = new ImageViewAdp(R.layout.imageview);
        recyclerVIew.setAdapter(adp);
        imageItem = new ImageItem();
        imageItem.name = "1";
        list.add(imageItem);
        adp.setNewData(list);

        adp.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (adp.getData().get(position).name.equals("1")) {
                    chooseImage();
                } else {
                    //打开预览
                    Intent intentPreview = new Intent(me, ImagePreviewDelActivity.class);
                    intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) adp.getData());
                    intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                    intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true);
                    startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                }
            }
        });
        TakePhotoUtil.getInstance(this).setReturnPhoto(new TakePhotoUtil.ReturnPhoto() {
            @Override
            public void onGetPhotos(String[] selectImagePaths) {
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).name.equals("1")) {
                        list.remove(i);
                    }
                }
                ImageItem item = new ImageItem();
                item.path = selectImagePaths[0];
                item.name = "3";
                item.addTime = 100000000;
                if (item != null) {
                    list.add(item);
                }
                if (list.size() < 4) {
                    list.add(imageItem);
                }
                adp.setNewData(list);
            }

            @Override
            public void onError(Exception e) {
                e.printStackTrace();
            }
        });
    }
    String see_count_account;
    private void moenyHttp() {
         HttpRequest.POST(me, "Index/moneyOfYue"
                         , new Parameter()
                                 .add("token", token)
                                 .add("type", 2)
                         , new ResponseListener() {
                     @Override
                     public void onResponse(String response, Exception error) {
                         if (error == null){
                             Map<String, String> map = JSONUtils.parseKeyAndValueToMap(response);
                             if (map.get("code").equals("1")){
                                 Map<String, String> data = JSONUtils.parseKeyAndValueToMap(map.get("data"));
                                 see_count_account = data.get("money");
                                 if (getSex.equals("1")) {
                                     text_renzheng.setText("会员免费，非会员需支付"+see_count_account+"元");
                                 } else {
                                     text_renzheng.setText("认证后免费发布，未认证需要支付"+see_count_account+"元");
                                 }

                             }

                         }
                     }
                 });
    }

    @OnClick({R.id.image_left_finish, R.id.text_expect, R.id.text_city, R.id.text_time, R.id.text_preservation
            , R.id.fl_time, R.id.text_can_comment})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.image_left_finish:
                finish();
                break;
            case R.id.text_expect:
                BottomDialog.start(this, "1", 2);
                break;
            case R.id.text_city:
                Intent intent2 = new Intent(this, CityListSelectActivity.class);
                startActivityForResult(intent2, 1);
                break;
            case R.id.text_time:
                //时间选择器
                TimePickerView pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        textTime.setText(getTime(date));
                    }
                }).setTitleText("日期选择")
                        .setSubmitText("确定")//确定按钮文字
                        .setCancelText("取消")//取消按钮文字
                        .setCancelColor(Color.GRAY)
                        .setSubmitColor(Color.RED)
                        .build();
                pvTime.show();
                break;
            case R.id.text_preservation:
                if (TextUtils.isEmpty(textExpect.getText().toString().trim())) {
                    ToastUtil.show("请选择期望对象！");
                    return;
                }
                if (TextUtils.isEmpty(editRemarks.getText().toString().trim())) {
                    ToastUtil.show("请输入备注说明！");
                    return;
                }
                if (TextUtils.isEmpty(textTime_1.getText().toString().trim())) {
                    ToastUtil.show("请选择时间！");
                    return;
                }
                if (TextUtils.isEmpty(textTime.getText().toString().trim())) {
                    ToastUtil.show("请选择日期！");
                    return;
                }
//                发布约会
                //男的
                if (getSex.equals("1")) {
                    // 是否vip 1否 2是
                    if (getVip.equals("1")) {
//                        dialog("10", "7", "");
                        setPay(see_count_account, "7");
                        return;
                    }
                } else {
                    if (getIdentification.equals("1")) {
                        setPay(see_count_account, "7");
                        return;
                    }
                }
                http();
                break;
            case R.id.fl_time:
                BottomDialog.start(this, "3", 10);
                break;
            case R.id.text_can_comment:
                //发布界面
                if (thisCont == 2) {
                    drawable = getResources().getDrawable(R.mipmap.icon_voice_broadcast_declaration);
                    thisCont = 1;
                } else {
                    drawable = getResources().getDrawable(R.mipmap.icon_voice_true);
                    thisCont = 2;
                }
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                textCanComment.setCompoundDrawables(null, null, drawable, null);
                break;
            default:
        }
    }

    private void http() {
//        token	用户token	否	文本	未提供
//        expect_ids	期望对象	否	文本	未提供
//        city	常驻城市 id	否	文本	未提供
//        appointment_time	约会日期	否	文本	未提供
//        appointment_am	约会时间 1上午 2中午 3下午 4晚上 5通宵 6一整天	否	文本	未提供
//        img[]	图片文件 最多4张	否	文本	未提供
//        remarks	备注	否	文本	未提供
//        can_comment	能否评论 1是 2否
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).name.equals("1")) {

            } else {
                if (i == 0) {
                    file1 = new File(list.get(i).path);
                } else if (i == 1) {
                    file2 = new File(list.get(i).path);
                } else if (i == 2) {
                    file3 = new File(list.get(i).path);
                } else if (i == 3) {
                    file4 = new File(list.get(i).path);
                }
            }
        }
        WaitDialog.show(me, "数据上传中");
        HttpRequest.POST(me, "Region/queryIdbyName"
                , new Parameter()
                        .add("region_name", textCity.getText().toString().trim())
                , new ResponseListener() {
                    @Override
                    public void onResponse(String response, Exception error) {
                        if (error == null) {
                            Map<String, String> map = JSONUtils.parseKeyAndValueToMap(response);
                            Map<String, String> data = JSONUtils.parseKeyAndValueToMap(map.get("data"));
                            if (map.get("code").equals("1")) {
                                if (data == null) {
                                    ToastUtil.show("网络出错");
                                    return;
                                }
                                if (textExpectId == null) {
                                    ToastUtil.show("期望对象不能为空！");
                                    return;
                                }
//                                能否评论 1是 2否   thisCont
                                HttpRequest.POST(me, "Order/addOrder"
                                        , new Parameter()
                                                .add("token", token)
                                                .add("expect_ids", textExpectId)
                                                .add("city", data.get("id"))
                                                .add("appointment_time", textTime.getText().toString().trim())
                                                .add("appointment_am", namappointment_ame)
                                                .add("img1", file1)
                                                .add("img2", file2)
                                                .add("img3", file3)
                                                .add("img4", file4)
                                                .add("remarks", editRemarks.getText().toString().trim())
                                                .add("can_comment", thisCont)
                                        , new ResponseListener() {
                                            @Override
                                            public void onResponse(final String response, Exception error) {
                                                if (error == null) {
                                                    Map<String, String> map = JSONUtils.parseKeyAndValueToMap(response);
                                                    if (map == null) {
                                                        WaitDialog.dismiss();
                                                        return;
                                                    }
                                                    if (map.get("code").equals("1")) {
                                                        TipDialog.show(me, map.get("message"), TipDialog.TYPE.SUCCESS).setOnDismissListener(new OnDismissListener() {
                                                            @Override
                                                            public void onDismiss() {
                                                                finish();
                                                                return;
                                                            }
                                                        });
                                                    } else {
                                                        ToastUtil.show(map.get("message"));
                                                        WaitDialog.dismiss();
                                                    }
                                                } else {
                                                    ToastUtil.show("网络错误");
                                                    WaitDialog.dismiss();
                                                }
                                            }
                                        });
                            }
                        }
                    }
                });
    }

    /**
     * 时间选择器
     */

    private String getTime(Date date) {
        //可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
//        SimpleDateFormat format = new SimpleDateFormat("MM月dd日 HH:mm");
        return format.format(date);
    }

    private ArrayList<ImageItem> images = null;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        TakePhotoUtil.getInstance(PublishAnAppoointmentActivity.this).onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            String city = bundle.getString("city");
//            cityId = bundle.getString("id");
            cityId = bundle.getString("city");
            textCity.setText(city);
        }
        if (requestCode == 2 && resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            textExpectId = bundle.getString("id");
            Log.d("textExpectId", "======textExpectId========" + textExpectId);
            String name = bundle.getString("name");
            textExpect.setText(name);
        }

        if (requestCode == 10 && resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            String name = bundle.getString("name");
            namappointment_ame = bundle.getString("appointment_am");
            textTime_1.setText(name);
        }

        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).name.equals("1")) {
                        list.remove(i);
                    }
                }
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null) {
                    list.addAll(images);
                }
                if (list.size() < 4) {
                    list.add(imageItem);
                }
                adp.setNewData(list);
            }
        } else if (resultCode == ImagePicker.RESULT_CODE_BACK) {
            //预览图片返回
            if (data != null && requestCode == REQUEST_CODE_PREVIEW) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                if (images != null) {
                    list.clear();
                    list.addAll(images);
                    if (list.size() < 4) {
                        list.add(imageItem);
                    }
                }
                adp.setNewData(list);
            }
        }

    }

    // 去选择图片
    private void chooseImage() {
        maxImgCount = 4;
        //打开选择,本次允许选择的数量
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).name.equals("1")) {

            } else {
                maxImgCount--;
            }
        }
        BottomMenu.show(this, new String[]{"拍照", "从相册里选择"}, new OnMenuItemClickListener() {
            @Override
            public void onClick(String text, int index) {
                switch (index) {
                    case 0:
                        TakePhotoUtil.getInstance(me).doOpenCamera();
                        break;
                    case 1:
                        ImagePicker.getInstance().setSelectLimit(maxImgCount);
                        Intent intent1 = new Intent(me, ImageGridActivity.class);
                        startActivityForResult(intent1, REQUEST_CODE_SELECT);
                        break;
                    default:
                }
            }
        });
    }

    public void setPay(String money, String type) {
        CustomDialog.build(me, R.layout.activity_pay_dialog2, new CustomDialog.OnBindView() {
            @Override
            public void onBind(final CustomDialog dialog, View v) {
                RecyclerView recyclerView = v.findViewById(R.id.recyclerView);
                List<PayNamePayBean> dialogList = new ArrayList<>();
                recyclerView.setLayoutManager(new LinearLayoutManager(me));
                PayAdapter payAdapter = new PayAdapter(R.layout.list_dialog_pay);
                recyclerView.setAdapter(payAdapter);
                dialogList.add(new PayNamePayBean("钱包支付", false, R.mipmap.ci_pay_wallet));
                dialogList.add(new PayNamePayBean("支付宝支付", false, R.mipmap.ic_pay_alipay));
                dialogList.add(new PayNamePayBean("微信支付", false, R.mipmap.ic_pay_wx));
                payAdapter.setNewData(dialogList);
                payAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                        List<PayNamePayBean> data = payAdapter.getData();
                        PayNamePayBean payNamePayBean = data.get(position);
                        if (payNamePayBean.getChoice() == true) {
                            payNamePayBean.setChoice(false);
                        } else {
                            for (int i = 0; i < data.size(); i++) {
                                data.get(i).setChoice(false);
                            }
                            payNamePayBean.setChoice(true);
                        }
                        payAdapter.notifyDataSetChanged();
                    }
                });

                TextView textDetermine = v.findViewById(R.id.text_determine);
                TextView textPrivateChat = v.findViewById(R.id.text_private_chat);
                ImageView imageBottomFinish = v.findViewById(R.id.image_bottom_finish);
                //钱数显示
                textPrivateChat.setText("￥" + money);

                textDetermine.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        pay(payAdapter, money, type);
                        dialog.doDismiss();
                    }
                });
                imageBottomFinish.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.doDismiss();
                    }
                });
            }
        }).setCancelable(false).show();
    }

    private void pay(PayAdapter payAdapter, String money, String type) {
        int payCount = -1;
        List<PayNamePayBean> data = payAdapter.getData();
        for (int i = 0; i < data.size(); i++) {
            if (data.get(i).getChoice() == true) {
                payCount = i;
            }
        }
        if (payCount == -1) {
            ToastUtil.show("请选择支付方式！");
            return;
        }
        Log.d("PayNamePayBean", "===================" + payCount);

//        1聊天或查看社交账号 2发布动态 4解锁相册 5开通会员 7发布约会
        //立即开通
        int finalPayCount = payCount;
        MessageDialog.show(me, "使用" + data.get(finalPayCount).name, "支付" + money + "元", "确认", "取消")
                .setOnOkButtonClickListener(new OnDialogButtonClickListener() {
                    @Override
                    public boolean onClick(BaseDialog baseDialog, View v) {
                        if (finalPayCount == 0) {
//                                    钱包支付
                            WaitDialog.show(me, "数据请求中");
                            qianbao(type, money);
                        } else if (finalPayCount == 1) {
//                                    支付宝支付
                            aliPay(type, money);
                        } else {
//                                    微信支付
                            wxPay(type, money);
                        }
                        return false;
                    }
                });
    }


    private void wxPay(String type, String money) {
        //        token	用户 token	否	文本	未提供
//        member_id	对方用户id 【type=1,3,4时】 选填	否	文本	未提供
//        type	1聊天或查看社交账号 2发布动态 4解锁相册 5开通会员	否	文本	未提供
//        money	金额	否	文本	未提供
//        meal_id	套餐id 【type=5时】 选填
        Model.getInstance().getUserApi().wxPay(token, money, type, "", "")
                .enqueue(new Callback<JsonObject>() {
                    @Override
                    public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
                        Map<String, String> map = Constants.codeGet(me, response);
                        if (map == null) {
                            return;
                        }
                        Map<String, String> data = JSONUtils.parseKeyAndValueToMap(map.get("data"));
                        if (data == null) {
                            return;
                        }
                        IWXAPI api = WXAPIFactory.createWXAPI(me, null);
                        api.registerApp(data.get("appid"));
                        PayReq req = new PayReq();
                        req.appId = data.get("appid");//你的微信appid
                        req.partnerId = data.get("partnerid");//商户号
                        req.prepayId = data.get("prepayid");
                        ;//预支付交易会话ID
                        req.nonceStr = data.get("noncestr");
                        ;//随机字符串
                        req.timeStamp = data.get("timestamp");
                        ;//时间戳
                        req.packageValue = data.get("package");//扩展字段,这里固定填写Sign=WXPay
                        req.sign = data.get("sign");
//                        req.order_code = data.get("order_code");
                        ;//签名
                        // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
                        api.sendReq(req);
                        publishAnAppoointment = 2;
                    }

                    @Override
                    public void onFailure(Call<JsonObject> call, Throwable t) {

                    }
                });
    }

    /**
     * 钱包支付
     */
    private void qianbao(String type, String money) {
        Model.getInstance().getUserApi().balancePay(token, "", type, money, "")
                .enqueue(new Callback<JsonObject>() {
                    @Override
                    public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
                        Map<String, String> map = Constants.codeGet(me, response);
                        if (map == null) {
                            return;
                        }
                        MessageDialog.show(me
                                , "提示"
                                , map.get("message")
                                , "知道了").setOkButton(new OnDialogButtonClickListener() {
                            @Override
                            public boolean onClick(BaseDialog baseDialog, View v) {
                                http();
//                                me.finish();
                                return false;
                            }
                        });
                    }

                    @Override
                    public void onFailure(Call<JsonObject> call, Throwable t) {

                    }
                });

    }

    /**
     * 支付宝支付
     */
    public void aliPay(String type, String money) {
//        token	用户 token	否	文本	未提供
//        member_id	对方用户id 【type=1,3,4时】 选填	否	文本	未提供
//        type	1聊天或查看社交账号 2发布动态 4解锁相册 5开通会员	否	文本	未提供
//        money	金额	否	文本	未提供
//        meal_id	套餐id 【type=5时】 选填
        Model.getInstance().getUserApi().aliPay(token, money, type, "", "")
                .enqueue(new Callback<JsonObject>() {
                    @Override
                    public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
                        Map<String, String> map = Constants.codeGet(me, response);
                        if (map == null) {
                            return;
                        }
                        Map<String, String> data = JSONUtils.parseKeyAndValueToMap(map.get("data"));
                        if (data == null) {
                            return;
                        }

                        final String pay_string = data.get("pay_string");
                        new Thread() {
                            @Override
                            public void run() {
                                super.run();
                                PayTask alipay = new PayTask(me);
                                Map<String, String> result = alipay.payV2(pay_string, true);
                                Message msg = new Message();
                                msg.what = SDK_PAY_FLAG;
                                msg.obj = result;
                                handler.sendMessage(msg);
                            }
                        }.start();
                    }

                    @Override
                    public void onFailure(Call<JsonObject> call, Throwable t) {

                    }
                });
    }

    private int SDK_PAY_FLAG = 1;


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            PayResult payResult = new PayResult((Map<String, String>) msg.obj);
            /**
             * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
             */
            String resultInfo = payResult.getResult();// 同步返回需要验证的信息
            String resultStatus = payResult.getResultStatus();
            // 判断resultStatus 为9000则代表支付成功
            if (TextUtils.equals(resultStatus, "9000")) {
                // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                http();
            } else {
                // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                ToastUtil.show("取消支付了");
            }
        }
    };


    @Override
    public void Success() {
        http();
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventMessage event) {
        //弹吐司显示EventBusActivity中提交事件的信息
        ToastUtil.show("支付成功");
        http();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}